import axios from "../../request/axios";
import React, { useEffect, useRef, useState } from "react";
import { Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import type { FormProps } from "antd";
import type { PopconfirmProps } from "antd";
import { Button, Form, Input, Empty, message, Popconfirm, Modal } from "antd";
import Modals from "../../components/Modal";
import SimpleMDE from "react-simplemde-editor";
import "easymde/dist/easymde.min.css";
import { PlusOutlined } from '@ant-design/icons';
import type { InputRef } from 'antd';
import { Flex, theme, Tooltip } from 'antd';
import { marked } from "marked";
import { useTranslation } from 'react-i18next';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

type FieldType = {
  keyword?: string;
  tag?: string;
  remember?: string;
};

function List() {
    const { t, i18n } = useTranslation();
  const [data, setdata] = useState<DataType[]>();
  const [tag, settag] = useState();
  const [keyword, setkeyword] = useState();

  const getlist = () => {
    axios({
      url: "http://blogapi.shbwyz.com/article/list",
      method: "get",
      params: {
        page: 1,
        pageSize: 6,
        keyword,
        tag,
      },
    }).then((res) => {
      console.log(res);
      setdata(res.data.rows);
    });
  };
  useEffect(() => {
    getlist();
  }, [tag, keyword]);

  const columns: TableProps<DataType>["columns"] = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? "geekblue" : "green";
            if (tag === "loser") {
              color = "volcano";
            }
            return (
              <Tag color={color} key={tag}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "浏览数",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "发布时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "发布时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },

    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showModal(record) }>查看</a>
          <a>编辑</a>
          <a>导出</a>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    setkeyword(values.keyword);
    settag(values.tag);
  };

  const confirm: PopconfirmProps["onConfirm"] = (e) => {
    console.log(e.id);
    axios({
      url: `http://blogapi.shbwyz.com/article/${e.id}`,
      method: "DELETE",
    }).then((res) => {
      console.log(res);
      message.success("Click on Yes");
      getlist();
    });
  };

  const cancel: PopconfirmProps["onCancel"] = (e) => {
    console.log(e);
    message.error("Click on No");
  };

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpenadd, setIsModalOpenadd] = useState(false);
  const [markedtext, setmarkedtext] = useState('');

  const showModal = (record) => {
    console.log(record);
    setmarkedtext(record.content)
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
// 添加
const [addval,setaddval] = useState('')
const [fwbval,setfwbval] = useState('')

  const showModaladd = () => {
    
    setIsModalOpenadd(true);
  };

  const handleOkadd = () => {

    setIsModalOpenadd(false);
    console.log(addval,addval,selectedTags);
    
    axios({
        url:'http://blogapi.shbwyz.com/article',
        method:'POST',
        data:{
            title:addval,
            content:addval,
            tags:selectedTags,
            categoryList:["HTTP"],
            authorId:47529555
        }
    }).then(res => {
        console.log(res);
        getlist();
    })
  };

  const handleCanceladd = () => {
    setIsModalOpenadd(false);
  };
// tag
const tagsData = ['NODE', '不想写了', 'JS', 'TS'];

  const [selectedTags, setSelectedTags] = React.useState<string[]>([]);
  const handleChange = (tag: string, checked: boolean) => {
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    console.log('You are interested in: ', nextSelectedTags);
    setSelectedTags(nextSelectedTags);
  };


//   

 const { token } = theme.useToken();
  const [tags, setTags] = useState<string[]>(['Unremovable', 'Tag 2', 'Tag 3']);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);
  const editInputRef = useRef<InputRef>(null);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [editInputValue]);

  const handleClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    console.log(newTags);
    setTags(newTags);
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && !tags.includes(inputValue)) {
      setTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = () => {
    const newTags = [...tags];
    newTags[editInputIndex] = editInputValue;
    setTags(newTags);
    setEditInputIndex(-1);
    setEditInputValue('');
  };

  const tagPlusStyle: React.CSSProperties = {
    height: 22,
    background: token.colorBgContainer,
    borderStyle: 'dashed',
  };
  return (
    <div>
      <div>
        <Form
          name="basic"
          layout="inline"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="keyword" name="keyword">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="tag" name="tag">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Button type="primary" onClick={showModaladd}>
                添加
            </Button>
        </Form>
      </div>
      <Table<DataType>
        columns={columns}
        dataSource={data}
        locale={{ emptyText: <Empty description="没有对应文章"></Empty> }}
      />
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div>
            <div dangerouslySetInnerHTML={{__html:marked(markedtext)}}></div>
        </div>
        
      </Modal>
      {/* 添加 */}
      <Modal
        title="Basic Modal"
        open={isModalOpenadd}
        onOk={handleOkadd}
        onCancel={handleCanceladd}
      >
        {tagsData.map<React.ReactNode>((tag) => (
        <Tag.CheckableTag
          key={tag}
          checked={selectedTags.includes(tag)}
          onChange={(checked) => handleChange(tag, checked)}
        >
          {tag}
        </Tag.CheckableTag>
      ))}
       {inputVisible ? (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={tagInputStyle}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      ) : (
        <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
          New Tag
        </Tag>
      )}
      <br />
      <input type="text" value={addval} onChange={(e)=>{setaddval(e.target.value)}}/>
        <SimpleMDE value={fwbval} onChange={(e)=>{setfwbval(e)}}>
            
        </SimpleMDE>
      </Modal>
    </div>
  );
}

export default List;
